package com.ejd.utils;

import java.util.Iterator;

import java.util.List;

import com.ejd.access.bean.Resource;

public class TreeUtil {
	public static final int INIT_TREE_LENGTH = 5;

	public static String getNextTreeCode(String parentCode, String treeCode) {
		int code = 0;
		treeCode = CommonUtil.isEmpty(treeCode) ? (parentCode + getZero(INIT_TREE_LENGTH)) : treeCode;
		if (treeCode.length() <= INIT_TREE_LENGTH) {
			code = Integer.parseInt(treeCode) + 1;
		} else {
			code = Integer.parseInt(treeCode.substring(treeCode.length() - INIT_TREE_LENGTH, treeCode.length())) + 1;
		}
		String addedZero = getZero(INIT_TREE_LENGTH - String.valueOf(code).length());
		
		return treeCode.substring(0, treeCode.length() - INIT_TREE_LENGTH) + addedZero + code;
	}
	
	private static String getZero(int length) {
		String zero = "";
		for (int i = 0; i < length; i++) {
			zero = zero + "0";
		}
		return zero;
	}
	
	public static StringBuffer getResourceTreeXml(List<Resource> list) throws Exception {
		if (list == null || list.isEmpty()) {
			return new StringBuffer();
		}
		String src = "resourceAction.html?method=treeItemStream";
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sb.append("<tree>");
		for (Iterator<Resource> it = list.iterator(); it.hasNext();) { 
			Resource resource = it.next();	
			String resourceName = resource.getName();
			resourceName = resourceName.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
			if (resource.isLeaf()) {
				sb.append("<tree text=\"" + resourceName + "\" isLeaf=\"true\" src=\"" + src + "&amp;ptreeCode=" + resource.getTreeCode() + "\" ");
				sb.append("action=\"javascript:go('" + resource.getTreeCode() + "')\"/>");
			} else {
				sb.append("<tree text=\"" + resourceName + "\" isLeaf=\"false\" src=\"" + src + "&amp;ptreeCode=" + resource.getTreeCode() + "\" ");
				sb.append("action=\"javascript:go('" + resource.getTreeCode() + "')\"/>");
			}
		}
		sb.append("</tree>");
		return sb;
	}
	
	public static String getTreeCode(Integer index) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < INIT_TREE_LENGTH - String.valueOf(index).length(); i++){
			sb.append("0");
		}
		sb.append(index);
		return sb.toString();
	}
	
	public static void main(String args[]) {
		System.out.println(getTreeCode(1));
	}
}
